import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_chat_ui/pages/agent_web_view_page/txh/txh_goods_list_page.dart';
import 'package:flutter_chat_ui/pages/agent_web_view_page/widgets/agent_chat_bottom_view.dart';
import 'package:flutter_chat_ui/pages/agent_web_view_page/app_call_h5_names.dart';
import 'package:flutter_chat_ui/routes/x_route.dart';

import 'package:flutter_plugin_agent_webview_bridge/flutter_plugin_agent_webview_bridge.dart';
import 'package:get/get.dart';

class AgentWebViewPage extends StatefulWidget {
  final String url;

  const AgentWebViewPage({
    super.key,
    required this.url,
  });

  @override
  State<AgentWebViewPage> createState() => _AgentWebViewPageState();
}

class _AgentWebViewPageState extends State<AgentWebViewPage> with AgentBridgeMethod {
  late String currentUrl; // 当前加载的页面url
  late final WebViewController _webViewController; // web的管理器
  late final AgentAppWebController _appWebController; // 桥接的管理器
  final ValueNotifier<bool> _isRespondingNotifier = ValueNotifier(false); // 是否机器人响应状态【默认false】

  @override
  void initState() {
    super.initState();
    currentUrl = widget.url;

    // web 配置
    _webViewController = WebViewController()
      ..setUserAgent(Platform.isAndroid
          ? 'Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36 i84'
          : 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 i84')
      ..enableZoom(true)
      ..setBackgroundColor(Colors.white)
      ..setNavigationDelegate(
        NavigationDelegate(
          onNavigationRequest: (request) => NavigationDecision.navigate,
          onProgress: (progress) {},
          onPageFinished: (String url) {
            print('WebView onPageFinished: ${url}');
          },
          onHttpError: (error) {
            print('WebView 加载错误: ${error}');
          },
          onWebResourceError: (error) {
            print('WebView 加载错误: ${error.description}');
          },
        ),
      )
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..loadRequest(Uri.parse(currentUrl))
      ..setOnJavaScriptAlertDialog((request) {
        return showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text('H5 Alert'),
              content: Text(request.message ?? '没有消息'),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: const Text('确定'),
                ),
              ],
            );
          },
        );
      });

    // 桥接web控制器
    _appWebController = AgentAppWebController(_webViewController, this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(
      //   backgroundColor: Colors.white,
      //   title: const Text("测试智能体"),
      // ),
      backgroundColor: Colors.white,
      body: Column(
        children: [
          /// webView
          Expanded(
              child: Padding(
            padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
            child: WebViewWidget(controller: _webViewController),
          )),

          /// 底部输入框
          ValueListenableBuilder<bool>(
            valueListenable: _isRespondingNotifier,
            builder: (context, value, child) {
              return AgentChatBottomView(
                isResponding: value,
                onSendMessage: (query) {
                  var params = {
                    "content": query,
                    "files": [],
                    "inputs": {
                      "cityCode": "350100",
                      "baseUrl": 'https://gateway.ngrok.i84.com.cn',
                      "token": "4b6a6ac7-1fc0-42f7-971a-978aa898c9bb",
                      "lng": "119.36043718168416",
                      "lat": "26.05814313700202",
                    },
                  };
                  final res = json.encode(params);
                  _appWebController.runJavaScript('${AppCallH5Names.sendEvokeAiAndSendMessage}($res)');
                },
              );
            },
          ),
        ],
      ),
    );
  }

  ///
  /// 获取智能体参数
  ///
  @override
  void getAIParams(AgentBridgeMessage message) {
    final params = {
      'apiKey': "app-zGTPb8HJkpIMi3dpYcAuKyz1",
      'user': "4b6a6ac7-1fc0-42f7-971a-978aa898c9bb",
      'baseUrl': "https://dify.frp.xlauch.com/v1",
      'imgDomain': "https://www.baidu.com",
      "mapKey": "",
    };
    message.data = params;
    _appWebController.jsSendMessage(message);
  }

  ///
  /// 发送消息loading状态
  ///
  @override
  void openSendLoading(AgentBridgeMessage message) {
    try {
      Map<String, dynamic> data = jsonDecode(message.data);
      bool isLoading = data['open'] ?? false;
      // 响应状态
      _isRespondingNotifier.value = isLoading;
    } catch (e) {
      print('openSendLoading解析失败: $e');
    }
  }

  ///
  /// 点击超链接，把内容发送给APP
  ///
  @override
  void sendLinkContext(AgentBridgeMessage message) {
    final data = message.data;
    if (data is String) {
      // 清理字符串
      final cleanedData = data.trim().replaceAll(RegExp(r'\s+'), '');
      try {
        final Map<String, dynamic> result = jsonDecode(cleanedData);
        final path = result['path'];

        if (path == XRouteNames.txhGoodsListPage) {
          Get.to(
            () => const TXHGoodsListPage(),
            routeName: XRouteNames.txhGoodsListPage,
          );
        }
      } catch (e) {
        print('sendLinkContext解析失败: $e');
      }
    }

    super.sendLinkContext(message);
  }

  ///
  /// 点击多媒体组件，把多媒体组件链接发送给APP
  ///
  @override
  void sendMediaSrc(AgentBridgeMessage message) {
    super.sendMediaSrc(message);
  }

  ///
  /// 新对话中，机器人回答的第一条聊天中的conversion_id
  ///
  @override
  void sendChatCID(AgentBridgeMessage message) {
    super.sendChatCID(message);
  }
}
